#include "widget.h"
#include "ui_widget.h"
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QVBoxLayout>
#include <QUrl>
#include <QClipboard>
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QApplication>
#include <QDebug>



Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->cancleButton_2,&QPushButton::clicked,this,&Widget::on_cancleButton_2_clicked);

    setWindowTitle("龙门发票打包工具(BillMaker)@by Kai Fang");
    ui->dateEdit->setDate(QDate::currentDate());
//    ui->DateLineEdit->setText("20230603");
    ui->BillNumerLineEdit->setText("654146504601");
    ui->NameLineEdit->setText("王林");
    ui->TotalPriceLineEdit->setText("897");
    ui->ObjectNameLineEdit->setText("舵机等");
    ui->UsageLineEdit->setText("无人机螺旋桨姿态调节");

    // 构造函数：初始化 pdf_pic 文件路径（这里使用exe主目录）
    QString exePath = QCoreApplication::applicationDirPath();
    QString filePath = exePath + "/tempFile";
    pdf_file.setFileName(filePath+"/pdf.pdf");
    taobao_pic.setFileName(filePath+"/taobao.png");
    bill_rec_pic.setFileName(filePath+"/bill.png");
    press_pic.setFileName(filePath+"/press.png");
    real_thing_pic.setFileName(filePath+"/real.png");


    // 启用 QLabel 接受拖放
   ui->TaoBaoBillPicFileNameLineEdit->setAcceptDrops(true);
   ui->billPDFFileNameLineEdit->setAcceptDrops(true);
   ui->billRecPicFileNameLineEdit->setAcceptDrops(true);
   ui->pressPicFileNameLineEdit->setAcceptDrops(true);
   ui->realThingPicFileNameLineEdit->setAcceptDrops(true);

   // 读取之前保存的内容
   QFile file("lineEditData.txt");
   if (file.exists() && file.open(QIODevice::ReadOnly)) {
       QTextStream in(&file);
//       ui->DateLineEdit->setText(in.readLine());  // 读取第一行
       QDate tmp_date = QDate::fromString(in.readLine(),"yyyyMMdd"); // 读取第一行
       ui->dateEdit->setDate(tmp_date);
       ui->BillNumerLineEdit->setText(in.readLine());  // 读取第二行
       ui->NameLineEdit->setText(in.readLine());  // 读取第三行
       ui->TotalPriceLineEdit->setText(in.readLine());
       ui->ObjectNameLineEdit->setText(in.readLine());
       ui->UsageLineEdit->setText(in.readLine());
       ui->billPDFFileNameLineEdit->setText(in.readLine());
       ui->TaoBaoBillPicFileNameLineEdit->setText(in.readLine());
       ui->billRecPicFileNameLineEdit->setText(in.readLine());
       ui->pressPicFileNameLineEdit->setText(in.readLine());
       ui->realThingPicFileNameLineEdit->setText(in.readLine());
       file.close();
   }

   // 更新预览
//   ui->displayLabel->setText(ui->DateLineEdit->text()+"-"+ui->BillNumerLineEdit->text()+"-"+
//                             ui->NameLineEdit->text()+"-"+ui->TotalPriceLineEdit->text()+"元-"+
//                             ui->ObjectNameLineEdit->text()+"-"+ui->UsageLineEdit->text());
   ui->displayLabel->setText(ui->dateEdit->date().toString("yyyyMMdd")+"-"+ui->BillNumerLineEdit->text()+"-"+
                             ui->NameLineEdit->text()+"-"+ui->TotalPriceLineEdit->text()+"元-"+
                             ui->ObjectNameLineEdit->text()+"-"+ui->UsageLineEdit->text());

   connect(ui->commitButton, &QPushButton::clicked, this, [this]() {
       QFile file("lineEditData.txt");
       if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
           QTextStream out(&file);
//           out << ui->DateLineEdit->text() << "\n";  // 保存第一行
           out << ui->dateEdit->date().toString("yyyyMMdd") << "\n";  // 保存第一行
           out << ui->BillNumerLineEdit->text() << "\n";  // 保存第二行
           out << ui->NameLineEdit->text() << "\n";  // 保存第三行
           out << ui->TotalPriceLineEdit->text() << "\n";
           out << ui->ObjectNameLineEdit->text() << "\n";
           out << ui->UsageLineEdit->text() << "\n";
           out << ui->billPDFFileNameLineEdit->text() << "\n";
           out << ui->TaoBaoBillPicFileNameLineEdit->text() << "\n";
           out << ui->billRecPicFileNameLineEdit->text() << "\n";
           out << ui->pressPicFileNameLineEdit->text() << "\n";
           out << ui->realThingPicFileNameLineEdit->text() << "\n";
           file.close();
       }
   });

}

Widget::~Widget()
{
    pdf_file.close();
    taobao_pic.close();
    bill_rec_pic.close();
    press_pic.close();
    real_thing_pic.close();
    delete ui;
}

void Widget::on_commitButton_clicked()
{
    auto isLineEditEmpty=[this]()->bool{
//        return ui->DateLineEdit->text().trimmed().isEmpty() || ui->BillNumerLineEdit->text().trimmed().isEmpty() || ui->NameLineEdit->text().trimmed().isEmpty() ||
//                ui->TotalPriceLineEdit->text().trimmed().isEmpty() || ui->ObjectNameLineEdit->text().trimmed().isEmpty() || ui->UsageLineEdit->text().trimmed().isEmpty() ||
//                  ui->billPDFFileNameLineEdit->text().trimmed().isEmpty() || ui->TaoBaoBillPicFileNameLineEdit->text().trimmed().isEmpty() || ui->billRecPicFileNameLineEdit->text().trimmed().isEmpty() ||
//                    ui->pressPicFileNameLineEdit->text().trimmed().isEmpty() || ui->realThingPicFileNameLineEdit->text().trimmed().isEmpty();
        return ui->BillNumerLineEdit->text().trimmed().isEmpty() || ui->NameLineEdit->text().trimmed().isEmpty() ||
                ui->TotalPriceLineEdit->text().trimmed().isEmpty() || ui->ObjectNameLineEdit->text().trimmed().isEmpty() || ui->UsageLineEdit->text().trimmed().isEmpty() ||
                  ui->billPDFFileNameLineEdit->text().trimmed().isEmpty() || ui->TaoBaoBillPicFileNameLineEdit->text().trimmed().isEmpty() || ui->billRecPicFileNameLineEdit->text().trimmed().isEmpty() ||
                    ui->pressPicFileNameLineEdit->text().trimmed().isEmpty() || ui->realThingPicFileNameLineEdit->text().trimmed().isEmpty();
    };
    if(isLineEditEmpty()){ QMessageBox::warning(this,"警告","信息不全或未选中文件！");return;}

    // 获取用户输入的文件夹名称
//       QString folderName = ui->DateLineEdit->text()+"-"+ui->BillNumerLineEdit->text()+"-"+
//               ui->NameLineEdit->text()+"-"+ui->TotalPriceLineEdit->text()+"元-"+
//               ui->ObjectNameLineEdit->text()+"-"+ui->UsageLineEdit->text();
    QString folderName = ui->dateEdit->date().toString("yyyyMMdd")+"-"+ui->BillNumerLineEdit->text()+"-"+
            ui->NameLineEdit->text()+"-"+ui->TotalPriceLineEdit->text()+"元-"+
            ui->ObjectNameLineEdit->text()+"-"+ui->UsageLineEdit->text();

        name_string[0]=folderName;

       // 弹出文件夹选择对话框
       QString targetDirectory = QFileDialog::getExistingDirectory(this, "选择目标文件夹", QDir::homePath());
       if (targetDirectory.isEmpty()) {
           QMessageBox::warning(this, "选择错误", "未选择目标文件夹！");
           return;
       }

       // 在目标文件夹下创建一个新的文件夹，名字为用户输入的字符串
       QDir dir(targetDirectory); // 新建了文件夹
       QString newFolderPath = QDir::toNativeSeparators(dir.filePath(folderName)); // folderName是短名,newFolderPath是完整名,使用原生分割保证不同系统的运行

       // 如果文件夹已存在，提示用户
       if (QDir(newFolderPath).exists()) {
           QMessageBox::warning(this, "文件夹已存在", "指定的文件夹已经存在！");
           return;
       }

       // 创建新文件夹
       if (!dir.mkdir(folderName)) {
           QMessageBox::critical(this, "创建文件夹失败", "无法创建目标文件夹！");
           return;
       }

       // 获取LineEdit中的文件路径列表，假设多个路径是以逗号分隔的
       QStringList filePaths;
       filePaths.append(ui->billPDFFileNameLineEdit->text());
       filePaths.append(ui->TaoBaoBillPicFileNameLineEdit->text());
       filePaths.append(ui->billRecPicFileNameLineEdit->text());
       filePaths.append(ui->pressPicFileNameLineEdit->text());
       filePaths.append(ui->realThingPicFileNameLineEdit->text());
       for (int i=0;i<filePaths.size();++i) {
           // 确保路径有效
           QFileInfo fileInfo(filePaths[i].trimmed());
           if (!fileInfo.exists()) {
               QMessageBox::warning(this, "无效路径", QString("文件路径不存在: %1").arg(filePaths[i]));
               continue;
           }

           // 生成目标文件的路径，重命名文件
           QString newFileName = generateNewFileName(fileInfo.fileName(),i);  // 你可以根据需要自定义这个命名规则
           QString newFilePath = QDir(newFolderPath).filePath(newFileName); // 将newFolderPath完整路径和自定义文件名连接

           // 复制文件到新文件夹并重命名
           if (!QFile::copy(filePaths[i].trimmed(), newFilePath)) {
               QMessageBox::warning(this, "文件复制失败", QString("无法复制文件: %1").arg(filePaths[i]));
           }
       }

       // 如果是材料报销,还需要拷贝 管理台账_XXX 和 验收单_XXX
       if(ui->checkMaterialBillBox->isChecked()){

           auto copyTableFile = [this,newFolderPath](QString docx_file_name){
               QString tmp_file_path = QDir(QCoreApplication::applicationDirPath()).filePath(docx_file_name+".docx"); // 找到exe路径下的TABLE_.docx
               if (!QFile::copy(tmp_file_path.trimmed(), QDir(newFolderPath).filePath(docx_file_name)+ui->NameLineEdit->text()+".docx")) { // TODO 没有在文件类型前加个人名字
                   QMessageBox::warning(this, "文件复制失败", QString("无法复制文件: %1").arg(tmp_file_path));
               }
           };

           copyTableFile("管理台账_");
           copyTableFile("验收单_");
       }

       QMessageBox::information(this, "操作完成", "文件已成功复制并重命名！");
}

QString Widget::generateNewFileName(const QString &originalFileName,int idx) {
    QString baseName = name_string[idx];
    QString suffix = QFileInfo(originalFileName).suffix(); // 文件后缀
    return baseName + "." + suffix;
}



void Widget::on_cancleButton_2_clicked()
{
    QFile file("lineEditData.txt");
    if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        QTextStream out(&file);
//        out << ui->DateLineEdit->text() << "\n";  // 保存第一行
        out << ui->dateEdit->date().toString("yyyyMMdd") << "\n";  // 保存第一行
        out << ui->BillNumerLineEdit->text() << "\n";  // 保存第二行
        out << ui->NameLineEdit->text() << "\n";  // 保存第三行
        out << ui->TotalPriceLineEdit->text() << "\n";
        out << ui->ObjectNameLineEdit->text() << "\n";
        out << ui->UsageLineEdit->text() << "\n";
        out << ui->billPDFFileNameLineEdit->text() << "\n";
        out << ui->TaoBaoBillPicFileNameLineEdit->text() << "\n";
        out << ui->billRecPicFileNameLineEdit->text() << "\n";
        out << ui->pressPicFileNameLineEdit->text() << "\n";
        out << ui->realThingPicFileNameLineEdit->text() << "\n";
        file.close();
    }
    this->close();
}

void Widget::on_PDFChooseButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,"选择发票PDF文件",QCoreApplication::applicationFilePath(),"*.pdf");
    if(fileName.isEmpty()) QMessageBox::warning(this,"警告","选择发票PDF文件!");
    else{
        pdf_file.setFileName(fileName);
        if (!pdf_file.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(this,"警告","文件选择失败！");
       }
        ui->billPDFFileNameLineEdit->setText(fileName);
    }
}


void Widget::on_BillPicChooseButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,"选择淘宝订单图片",QCoreApplication::applicationFilePath());
    if(fileName.isEmpty()) QMessageBox::warning(this,"警告","选择淘宝订单图片!");
    else{
        taobao_pic.setFileName(fileName);
        if (!taobao_pic.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(this,"警告","文件选择失败！");
       }
        ui->TaoBaoBillPicFileNameLineEdit->setText(fileName);
    }
}


void Widget::on_BillRecChooseButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,"选择付款记录图片",QCoreApplication::applicationFilePath());
    if(fileName.isEmpty()) QMessageBox::warning(this,"警告","选择付款记录图片!");
    else{
        bill_rec_pic.setFileName(fileName);
        if (!bill_rec_pic.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(this,"警告","文件选择失败！");
       }
        ui->billRecPicFileNameLineEdit->setText(fileName);
    }
}


void Widget::on_PressPicChooseButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,"选择快递物流图片",QCoreApplication::applicationFilePath());
    if(fileName.isEmpty()) QMessageBox::warning(this,"警告","选择快递物流图片!");
    else{
        press_pic.setFileName(fileName);
        if (!pdf_file.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(this,"警告","文件选择失败！");
       }
        ui->pressPicFileNameLineEdit->setText(fileName);
    }
}

void Widget::on_RealThingPicChooseButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,"选择实物图片",QCoreApplication::applicationFilePath());
    if(fileName.isEmpty()) QMessageBox::warning(this,"警告","选择实物图片!");
    else{
        real_thing_pic.setFileName(fileName);
        if (!real_thing_pic.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(this,"警告","文件选择失败！");
       }
        ui->realThingPicFileNameLineEdit->setText(fileName);
    }
}

// 处理拖动进入事件
void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    // 判断是否为文件拖放
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

// 处理拖放事件
void Widget::dropEvent(QDropEvent *event)
{
    // 获取拖放的文件路径
    QList<QUrl> urls = event->mimeData()->urls();
    if (!urls.isEmpty()) {
        QString filePath = urls.first().toLocalFile();  // 获取文件路径
        QFileInfo fileInfo(filePath);

        // 判断拖放目标是哪个 QLineEdit
        if (event->source() == ui->TaoBaoBillPicFileNameLineEdit) {
            ui->TaoBaoBillPicFileNameLineEdit->setText(fileInfo.fileName());  // 设置文件名到 QLineEdit_1
        } else if (event->source() == ui->billPDFFileNameLineEdit) {
            ui->billPDFFileNameLineEdit->setText(fileInfo.fileName());  // 设置文件名到 QLineEdit_2
        } else if (event->source() == ui->pressPicFileNameLineEdit) {
            ui->pressPicFileNameLineEdit->setText(fileInfo.fileName());  // 设置文件名到 QLineEdit_2
        } else if (event->source() == ui->realThingPicFileNameLineEdit) {
            ui->realThingPicFileNameLineEdit->setText(fileInfo.fileName());  // 设置文件名到 QLineEdit_2
        }else if (event->source() == ui->billRecPicFileNameLineEdit) {
            ui->billRecPicFileNameLineEdit->setText(fileInfo.fileName());  // 设置文件名到 QLineEdit_2
        }
    }
}


bool PasteFileOperation(QFile &qfile,QLineEdit* line_edit){
    // 获取剪贴板
       QClipboard *clipboard = QApplication::clipboard();
       const QMimeData *mimeData = clipboard->mimeData();

       // 检查剪切板是否包含文件
       if (mimeData->hasUrls()) {
           // 获取剪贴板中的文件 URL 列表
           QList<QUrl> urls = mimeData->urls();

           // 确保列表不为空
           if (!urls.isEmpty()) {
               // 获取第一个文件的路径
               QString sourceFilePath = urls.first().toLocalFile();

               // 检查路径有效性
               if (sourceFilePath.isEmpty()) {
//                   QMessageBox::warning(nullptr, "警告", "剪切板中的文件路径无效！");
                   return false;
               }

               //  QFile 对象，并赋值为剪贴板中的文件路径
               qfile.setFileName(sourceFilePath);

               // 检查文件是否存在
               if (!qfile.exists()) {
//                   QMessageBox::warning(nullptr, "警告", "源文件不存在！");
                   return false;
               }

               // 更新LineEdit
               line_edit->setText(sourceFilePath);

           }
       } else {
//           QMessageBox::warning(nullptr, "警告", "剪切板中没有文件！");
           return false;
       }
       return true;
}

void Widget::on_PDFPasteButton_clicked()
{
   PasteFileOperation(pdf_file,ui->billPDFFileNameLineEdit);
}

bool PastePicOperation(QFile &qfile,QLineEdit* line_edit,QString tmp_file_name){
    qfile.setFileName(tmp_file_name);
    // 获取剪贴板
   QClipboard *clipboard = QApplication::clipboard();
   const QMimeData *mimeData = clipboard->mimeData();

   // 检查剪贴板中是否包含图像
   if (mimeData->hasImage()) {
       // 获取剪贴板中的图像数据
       QImage image = qvariant_cast<QImage>(mimeData->imageData());

       // 检查图像是否有效
       if (image.isNull()) {
//           QMessageBox::warning(nullptr, "警告", "剪贴板中的图像无效！");
           return false;
       }

       // 确保目录存在
       QString dirPath = qfile.fileName().left(qfile.fileName().lastIndexOf('/'));
       QDir dir(dirPath);
       if (!dir.exists()) {
           if (!dir.mkpath(dirPath)) {
//               QMessageBox::critical(nullptr, "错误", "无法创建目录！");
               return false;
           }
       }

       // 如果 pdf_pic 文件已经打开，先关闭它
       if (qfile.isOpen()) {
           qfile.close();
       }

       // 打开 pdf_pic 文件进行写入
       if (qfile.open(QIODevice::WriteOnly)) {
           // 将 QImage 保存到 pdf_pic 文件
           if (image.save(&qfile)) {
               line_edit->setText(qfile.fileName());
           } else {
//               QMessageBox::critical(nullptr, "错误", "保存截图失败！");
               return false;
           }
           qfile.close();
       } else {
//           QMessageBox::critical(nullptr, "错误", "无法打开文件保存路径！");
           return false;
       }
   } else {
//       QMessageBox::warning(nullptr, "警告", "剪贴板中没有图像！");
       return false;
   }
   return true;
}

void Widget::on_TaobaoPasteButton_clicked()
{
    if(!PastePicOperation(taobao_pic,ui->TaoBaoBillPicFileNameLineEdit,QCoreApplication::applicationDirPath()+"/tempFile/taobao.png"))
        PasteFileOperation(taobao_pic,ui->TaoBaoBillPicFileNameLineEdit);
}


void Widget::on_BillRecPasteButton_clicked()
{
    if(!PastePicOperation(bill_rec_pic,ui->billRecPicFileNameLineEdit,QCoreApplication::applicationDirPath()+"/tempFile/bill.png"))
        PasteFileOperation(bill_rec_pic,ui->billRecPicFileNameLineEdit);
}


void Widget::on_PressPasteButton_clicked()
{
    if(!PastePicOperation(press_pic,ui->pressPicFileNameLineEdit,QCoreApplication::applicationDirPath()+"/tempFile/press.png"))
        PasteFileOperation(press_pic,ui->pressPicFileNameLineEdit);
}


void Widget::on_RealThingPasteButton_clicked()
{
    if(!PastePicOperation(real_thing_pic,ui->realThingPicFileNameLineEdit,QCoreApplication::applicationDirPath()+"/tempFile/real.png"))
        PasteFileOperation(real_thing_pic,ui->realThingPicFileNameLineEdit);
}

// 结束操作后进行保存和更新预览
void Widget::finishEditOperation(){
    QFile file("lineEditData.txt");
    if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        QTextStream out(&file);
        out << ui->dateEdit->date().toString("yyyyMMdd") << "\n";  // 保存第一行
        out << ui->BillNumerLineEdit->text() << "\n";  // 保存第二行
        out << ui->NameLineEdit->text() << "\n";  // 保存第三行
        out << ui->TotalPriceLineEdit->text() << "\n";
        out << ui->ObjectNameLineEdit->text() << "\n";
        out << ui->UsageLineEdit->text() << "\n";
        out << ui->billPDFFileNameLineEdit->text() << "\n";
        out << ui->TaoBaoBillPicFileNameLineEdit->text() << "\n";
        out << ui->billRecPicFileNameLineEdit->text() << "\n";
        out << ui->pressPicFileNameLineEdit->text() << "\n";
        out << ui->realThingPicFileNameLineEdit->text() << "\n";
        file.close();
    }
    ui->displayLabel->setText(ui->dateEdit->date().toString("yyyyMMdd")+"-"+ui->BillNumerLineEdit->text()+"-" \
                              +ui->NameLineEdit->text()+"-"+ui->TotalPriceLineEdit->text()+"元-" \
                              +ui->ObjectNameLineEdit->text()+"-"+ui->UsageLineEdit->text());
}

// 结束操作后进行保存和更新预览
//void Widget::on_DateLineEdit_editingFinished()
//{
//  finishEditOperation();
//}

// 结束操作后进行保存和更新预览
void Widget::on_BillNumerLineEdit_editingFinished()
{
  finishEditOperation();
}

// 结束操作后进行保存和更新预览
void Widget::on_NameLineEdit_editingFinished()
{
  finishEditOperation();
}

// 结束操作后进行保存和更新预览
void Widget::on_TotalPriceLineEdit_editingFinished()
{
  finishEditOperation();
}

// 结束操作后进行保存和更新预览
void Widget::on_ObjectNameLineEdit_editingFinished()
{
  finishEditOperation();
}

// 结束操作后进行保存和更新预览
void Widget::on_UsageLineEdit_editingFinished()
{
  finishEditOperation();
}

// 结束操作后进行保存和更新预览
void Widget::on_dateEdit_editingFinished()
{
    finishEditOperation();
}

